using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace BusinessLibrary
{
	public class TcpCommand
	{
		Socket _socket;
        NetworkStream _stream;
		int readCount = 10;
		
		public TcpCommand ()
		{
		}
		
		public virtual void Connect(string ipnumber, int portnumber)
		{
			try
            {
                //create a new client socket ...
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(ipnumber);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, portnumber);
                _socket.Connect(remoteEndPoint);
            }
            catch
            {
				throw new Exception("连接远程主机失败。");
            }
		}
		
		public void SendMessage(string msg)
		{
		    try
            {
				msg += "\r\n";
                _stream = new NetworkStream(_socket); 
				_stream.Write(Encoding.UTF8.GetBytes(msg), 0, msg.Length);
                _stream.Flush();
            }
            catch 
            {
               throw new Exception("发送消息失败。");
            }
			finally
			{
				_stream.Close ();
			}
		}
		
		public string ReadMessage()
		{
			string str = string.Empty;
			try
            {
                _stream = new NetworkStream(_socket); 
                //_stream.ReadTimeout = 20000;// 20秒
				//if(_stream.CanRead && _stream.DataAvailable)
				//{
				//Output("请稍候....");
				byte[] bs = new byte[readCount];
				_stream.Read(bs, 0, readCount);
				str = System.Text.Encoding.UTF8.GetString(bs);
				//}
            }
            catch
            {
				throw new Exception("读取消息失败。");
			}
			finally
			{
				_stream.Close ();
			}
			
			return str;
		}
	}
}

